package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.excption.MyException;
import com.itheima.pojo.OmsOrderReturnApply;
import com.itheima.pojo.OmsOrderReturnReason;
import com.itheima.vo.PageResultVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OmsOrderReturnReasonService {
    @DubboReference
    private OmsOrderReturnReasonApi reasonApi;
    @DubboReference
    private OmsOrderReturnApplyApi applyApi;

    //添加退货理由
    public void create(OmsOrderReturnReason reason) {
        //校验添加的原因唯一
        List<OmsOrderReturnReason> reasons = reasonApi.getAllReason();
        //没有原因,直接添加,并退出方法
        if (ObjectUtil.isEmpty(reasons)) {
            reasonApi.create(reason);
            return;
        }
        List<String> names = CollUtil.getFieldValues(reasons, "name", String.class);
        for (String name : names) {
            if (StringUtils.equals(reason.getName(), name)) throw new MyException("该原因已存在");
        }
        //添加
        reasonApi.create(reason);
    }

    //删除退货理由
    public void delete(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) throw new MyException("无可用id");
        List<OmsOrderReturnApply> applies = applyApi.findAll();
        //已用的原因
        List<String> reasons = CollUtil.getFieldValues(applies, "reason", String.class);
        //准备删除的原因
        List<OmsOrderReturnReason> returnReasons = reasonApi.getReasonByids(ids);
        List<String> names = CollUtil.getFieldValues(returnReasons, "name", String.class);
        //如果删除的原因里有已用原因,不能删除
        for (String name : names) {
            for (String reason : reasons) {
                if (StringUtils.equals(reason, name)) throw new MyException("退货原因正在使用,无法删除");
            }
        }
//现在批量删除
        reasonApi.deleteByIds(ids);
    }

    //分页查询
    public PageResultVo list(Integer pageNum, Integer pageSize) {
        return reasonApi.list(pageNum, pageSize);
    }

    //修改状态
    public void updateStatus(Integer ids, Integer status) {
        if (status == 1) {
            reasonApi.updateStatus(ids, status);
            return;
        }
        OmsOrderReturnReason reasonByid = reasonApi.findByid(Long.valueOf(ids));
        List<OmsOrderReturnApply> applies = applyApi.findAll();
        //已用的原因
        List<String> reasons = CollUtil.getFieldValues(applies, "reason", String.class);
        for (String reason : reasons) {
            if (StringUtils.equals(reasonByid.getName(), reason)) throw new MyException("不能禁用已用的退货原因");
        }
        //没有使用这个原因,可以禁用
        reasonApi.updateStatus(ids, status);
    }

    public void updateByid(OmsOrderReturnReason reason) {
        reasonApi.updateByid(reason);
    }

    public OmsOrderReturnReason findById(Long id) {
        return reasonApi.findByid(id);
    }
}
